package com.nyist.myticket.web.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * *
 *
 * @author yangxiaogen
 * @date 2022/3/3 11:42
 */
@Slf4j
@Component
public class MyEncodingFilter implements Filter {
    private FilterConfig filterConfig = null;
    private String encoding = null;

    String[] excludedUrl;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        this.encoding = filterConfig.getInitParameter("encoding");
        // this.excludedUrl = filterConfig.getInitParameter("excludedUrl").split(",");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        ServletContext context = this.filterConfig.getServletContext();
        context.log("=====> 设置请求编码格式");

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        String encoding = getEncoding();
        if (encoding == null) {
            encoding = "gb2312";
        }

        request.setCharacterEncoding(encoding);

        try {
            log.info("设置请求编码格式 过滤器被调用了.........请求地址为: {}",request.getRequestURI());
            chain.doFilter(request, response);
            context.log("=====> 设置请求编码格式 成功");
        } catch (Exception e) {
            log.error("=====> 调用过滤链异常,异常信息为: {}", e.getMessage());
        }

    }

    @Override
    public void destroy() {
        this.encoding = null;
    }

    public String getEncoding() {
        return encoding;
    }
}
